package com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor;

import java.io.File;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.romotc.joyin.bean.Customer;
import com.romotc.joyin.bean.CustomerService;
import com.romotc.joyin.bean.MemberCustService;
import com.romotc.json.tools.Jackson;
import com.romotc.os.RunOsCmd;
import com.romotc.qqrobot.bean.MemberCustServiceService;
import com.romotc.qqrobot.bean.PollResult;
import com.romotc.qqrobot.bean.PollResultService;
import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.bean.QQTask;
import com.romotc.qqrobot.bean.QQUserFriend;
import com.romotc.qqrobot.bean.QQUserFriendService;
import com.romotc.qqrobot.bean.RobotUser;
import com.romotc.qqrobot.bean.RobotUserService;
import com.romotc.qqrobot.webqq.bean.Get_friend_uin_ResponseBody;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Get_file2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Get_friend_uin2_GetQQNumFromTuin_InterCall;
import com.romotc.scache.RequestSpy;

public class SaveFile_Processor implements DateProcessor {

	public static final String Key_File_Path = "FileSavePath";


	@Override
	public JSONObject processResponse(QQLogedin loginQQ, RequestSpy rqSpy,
			JSONObject reqDataObj) throws Exception {
		if(rqSpy == null || rqSpy.cacheFile == null)
			return reqDataObj;
		
		File cacheFile = new File(rqSpy.cacheFile);
		if(!cacheFile.exists())
			return reqDataObj;
		
		//文件保存 路径： 接受人/发送人/消息Id/文件名
		String recer = loginQQ.getUin();
		long sender = reqDataObj.getLong(Get_file2_InterCall.Key_Must_Input_SenderUin);
		String senderInfo = String.valueOf(sender);
		
		long uid = RobotUserService.qryUidByQQNum(recer);
		RobotUser rUser = RobotUserService.qryUser(uid);
		
		Customer cust = null;
		//查询对应的好友 客户信息 
		QQUserFriend quf = QQUserFriendService.qryQFriendByUin(loginQQ.getId(), sender);
		String senderQQ = "";
		if(quf != null && StringUtils.isNotBlank(quf.getMarkname())) {
			String markName = quf.getMarkname();
			senderQQ = quf.getQqNum();
			if(StringUtils.isNotBlank(markName)) {
				senderInfo = markName;
			}
			
			if(StringUtils.isNotBlank(senderQQ)) {
				senderInfo += "[" + senderQQ + "]";
			}else {
				cust = CustomerService.qryCustomerByName(markName, uid);
				senderQQ =  cust.getQqNum();
				senderInfo += "[" + cust.getQqNum() + "]";
			}
		}else {
			//没有查到好友信息 再掉接口获取发送人的QQ号
			//检查好友 与 客户对应关系
			Get_friend_uin2_GetQQNumFromTuin_InterCall getQNumCall = Get_friend_uin2_GetQQNumFromTuin_InterCall.getInstance();
			JSONObject reqData = new JSONObject();
			
				reqData.put(getQNumCall.Key_Must_Input_Tuin, sender);
				
				reqData = getQNumCall.call(loginQQ, reqData,new DateProcessor(){

					@Override
					public JSONObject processResponse(QQLogedin loginQQ,
							RequestSpy rqSpy, JSONObject reqDataObj)
							throws Exception {
						// {"retcode":0,"result":{"uiuin":"","account":819512594,"uin":1924492178}}
						String resBody = rqSpy.getResBody();
						Get_friend_uin_ResponseBody resObject = Jackson.getObjectMaper().readValue(resBody, Get_friend_uin_ResponseBody.class);
						if(resObject.getRetcode() == 0 && resObject.getResult() != null) {
							//不正常的返回信息：QQ号
							if(resObject.getResult().getAccount() < 10000) {
								
							}else {
								reqDataObj.put("QQNum", resObject.getResult().getAccount());
							}
							
						}
						return reqDataObj;
					}
					
				});
				
				String qqNum = reqData.getString("QQNum");
				if(StringUtils.isNotBlank(qqNum)) {
					cust = CustomerService.qryCustomerByQNum(uid, qqNum);
					if(cust != null) {
						senderInfo = cust.getCustName() + "[" + qqNum + "]";
					}else
					{
						senderInfo = qqNum;
					}
				}
		}
		
		int lcid = reqDataObj.getInt(Get_file2_InterCall.Key_Must_Input_Lcid);
		
		String fileName = reqDataObj.getString(Get_file2_InterCall.Key_Must_Input_FileName);
		
		//
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		String curDate = fmt.format(new Date());//当前日期
		String dirPath = "fileRev" 
			+ File.separator + rUser.getUserName() //5798.cc
			+ File.separator + curDate
			+ File.separator + recer //号
			+ File.separator + senderInfo //发送文件的客户名(发送人QQ号)
			+ File.separator;
		
		File file = new File(dirPath);
		System.out.println(file.getAbsolutePath());
		dirPath = file.getAbsolutePath() + File.separator;
		boolean b = false;
		if(!file.exists())
			b = file.mkdirs();
		
		file = new File(dirPath + lcid + "-" + fileName);
		
		FileUtils.copyFile(cacheFile, file);
		//cacheFile.renameTo(file); do not work on linux
		System.err.println("File saved :" + file.getName() + "@" + file.getParent());
		reqDataObj.put(Key_File_Path , file.getAbsolutePath());
		
		//给相应的客服人员文件下载目录中创建软连接
		String lnFilePath = dirPath.replace(curDate, "CustServiceDL");
		//查询对应的客服
		MemberCustService custService = MemberCustServiceService.qryCustServiceByCustQNum(uid, senderQQ);
		if(custService == null) {
			custService = new MemberCustService();
			custService.setCsId(9999);
		}
		
		lnFilePath = lnFilePath.replace(recer, String.valueOf(custService.getCsId()));
		File lnFolder = new File(lnFilePath);
		if(!lnFolder.exists()) {
			lnFolder.mkdirs();
		}
		lnFilePath += lcid + "-" + fileName;
		System.out.println(lnFilePath);
		RunOsCmd.runCmd("ln -s " + dirPath + lcid + "-" + fileName + " " + lnFilePath);
		
		
		//文件接受完毕 给客服发送一条消息
//		PollResultService.sendFileRecvedMsg2CustService(custService, lnFilePath);
		PollResult msg = new PollResult();
		if(cust != null)
			msg.setCustId(cust.getId());
		msg.setCustServiceId(custService.getId());
		msg.setMsgTime(new Timestamp(System.currentTimeMillis()));
		msg.setPoll_type("message");//文件保存后给客服的通知 类型
		msg.setFrom_uin(sender);//发送文件人的Uin
		msg.setTo_uin(Long.valueOf(recer));//接受文件的Qq号码
		msg.setMsg_type(9);//文件保存后给客服的通知 类型
		msg.setContentMsg("文件接受完成：" + lnFilePath);//给客服人员看的文件链接位置
		PollResult lastMsg = PollResultService.qryLastMsg(sender);
		msg.setMsg_id2(lastMsg.getMsg_id2() + 1);
		msg.Save();
		
		
		return reqDataObj;
	}


	private static SaveFile_Processor instance;
	public static synchronized SaveFile_Processor getInstance() {
		if(instance == null)
			instance = new SaveFile_Processor();
		return instance;
	}
	
	public static void main(String[] args) throws Exception{
		String filePath = "./aaaa/aaaa/ddd/aaa";
		File f = new File(filePath);
		if(!f.exists())
			f.mkdirs();
		
		f = new File(filePath + "/test.txt");
		f.createNewFile();
		
		
	}

}
